package com.chance.cc.crawler.development.command.trigger;

import com.alibaba.fastjson.JSON;
import com.chance.cc.crawler.development.command.HttpCommand;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.downloader.HttpRequestBody;
import com.chance.cc.crawler.meta.core.bean.trigger.CrawlerScheduleTrigger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * created by CC on 2020/11/26
 * mail 279020185@qq.com
 */
@Slf4j
public class CrawlerJobTriggerCommand extends com.chance.cc.crawler.development.command.HttpCommand {

    public CrawlerJobTriggerCommand(String host, int port){
        super(host,port);
    }

    public HttpPage addOrUpdateScheduleCrawlerTrigger(String crawlerKey,
                                                      String crawlerTriggerKey,
                                                      String domain,
                                                      String triggerType,
                                                      String triggerExp,
                                                      String note){
        String url = commandUrl("addOrUpdateCrawlerScheduleTrigger");

        CrawlerScheduleTrigger crawlerScheduleTrigger = new CrawlerScheduleTrigger();
        crawlerScheduleTrigger.setDomain(domain);
        crawlerScheduleTrigger.setCrawlerKey(crawlerKey);
        crawlerScheduleTrigger.setCrawlerTriggerKey(crawlerTriggerKey);
        crawlerScheduleTrigger.setStatus(0);
        crawlerScheduleTrigger.setTriggerType(triggerType);
        crawlerScheduleTrigger.setTriggerExp(triggerExp);
        crawlerScheduleTrigger.setNote(note);

        //generate request
        HttpRequest request = new HttpRequest();
        request.setUrl(url);
        request.setMethod(HttpConstant.Method.POST);
        request.setRequestBody(HttpRequestBody.json(JSON.toJSONString(crawlerScheduleTrigger),"utf-8"));
        HttpPage httpPage = doCommand(request);
        log.info("trigger info publish result :{}",httpPage.getRawText());
        return httpPage;
    }

    @Override
    public String initUrlPrefix(String host,int port) {
        return StringUtils.join("http://",host,":",port,"/crawler/trigger/api/v1");
    }
}
